package com.shz.appletsapi.service;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Date;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shz.appletsapi.common.utils.DateUtils;
import com.shz.appletsapi.model.po.LahuoMonitor;
import com.shz.appletsapi.repository.LahuoMonitorRepository;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class LahuoMonitorReceiver {
	
	@Autowired
	private LahuoMonitorRepository lahuoMonitorRepository;
	
	@RabbitListener(queues="lahuo.monitor")
	public void process(byte[] bytes) throws Exception {
		LahuoMonitor monitor =  (LahuoMonitor) getObjectFromBytes(bytes);
		log.info("接受到"+monitor);
		
		LahuoMonitor lahuoMonitor = lahuoMonitorRepository.findByAppIdAndCreateDateAndContent(monitor.getAppId(),DateUtils.getDate(),monitor.getContent());
		
		if(lahuoMonitor != null) {
			lahuoMonitor.setCount(lahuoMonitor.getCount()+1);
		}else {
			lahuoMonitor =new LahuoMonitor();
			lahuoMonitor.setAppId(monitor.getAppId());
			lahuoMonitor.setContent(monitor.getContent());	
			lahuoMonitor.setCount(1);
			lahuoMonitor.setCreateDate(new Date());
			lahuoMonitor.setCreateTime(new Date());
		}
		
		lahuoMonitorRepository.save(lahuoMonitor);
		log.info("ok");
		
	}
	
	public  Object getObjectFromBytes(byte[] objBytes) throws Exception {
        if (objBytes == null || objBytes.length == 0) {
            return null;
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
        ObjectInputStream oi = new ObjectInputStream(bi);
        return oi.readObject();
    }


}
